<template>
	<div class="tree-container">
		<!-- 树结构渲染 -->
		<el-tree
			ref="treeRef"
			:data="treeData"
			node-key="chapterNo"
			:props="defaultProps"
			:default-expand-all="expandAll"
			:expand-on-click-node="false"
			:highlight-current="true"
			:current-node-key="currentNodeKey"
			@node-click="handleNodeClick"
		>
			<template #default="{ node, data }">
				<div class="custom-tree-node">
				  <span class="node-label">
					{{ node.label }}
					<span class="node-meta" v-if="data.orderNum || data.chapterNo">
					  {{ data.orderNum ? '['+data.orderNum+']' : '' }}
					  {{ data.chapterNo ? '('+data.chapterNo+')' : '' }}
					</span>
				  </span>

					<div class="node-actions" v-if="btn">
						<el-button
							size="small"
							type="primary"
							link
							@click.stop="() => append(data)"
							class="action-btn"
							:disabled="getNodeLevel(data) >= props.maxLevel"
						>
						<el-icon><Plus /></el-icon>
						</el-button>
						<el-button
							size="small"
							type="primary"
							link
							@click.stop="() => startEdit(data)"
							class="action-btn"
						>
							<el-icon><Edit /></el-icon>
						</el-button>
						<el-button
							size="small"
							type="danger"
							link
							@click.stop="() => remove(node, data)"
							class="action-btn"
						>
							<el-icon><Delete /></el-icon>
						</el-button>
					</div>
				</div>
			</template>
		</el-tree>
	</div>
	<div class="content-wrap" v-if="tab=='course'">
		<graph :key="chapterNo" :chapterNo="chapterNo"></graph>
	</div>
	<div class="content-wrap" v-else>
		<el-empty description="暂无相关课程视频" />
	</div>
	<el-drawer v-model="editDialogVisible" :title="isAdd ? '新增子节点' : '编辑节点'" :with-header="true">
		<el-form ref="editFormRef" :model="editFormData" label-width="80px" :rules="formRules">
			<el-form-item label="章节名称" prop="name">
				<el-input v-model="editFormData.name" placeholder="请输入章节名称" />
			</el-form-item>
			<el-form-item label="序号" prop="orderNum">
				<el-input-number v-model="editFormData.orderNum" :min="1" placeholder="排序序号" />
			</el-form-item>
			<el-form-item label="章节编号" prop="chapterNo">
				<el-input-number v-model="editFormData.chapterNo" :min="1" placeholder="章节编号" />
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="confirmEdit">确定</el-button>
				<el-button @click="cancelEdit">取消</el-button>
			</el-form-item>
		</el-form>
	</el-drawer>
</template>

<script lang="ts" setup>
import { ref, reactive, watch, nextTick, computed, onMounted, onUnmounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete } from '@element-plus/icons-vue'

import graph from '../../modules/course/views/graph.vue'
// 后端要求的章节数据格式
interface BackendChapter {
	courseNo?: number;       // 课程编号
	bookNo?: number;       // 教材编号
	chapterNo: number;    // 章节编号（用于关联子节点的parentNo）
	children?: BackendChapter[]; // 子章节
	id: number|'';        // 节点ID
	name: string;         // 章节名称
	orderNum: number;     // 排序序号
	parentNo: number;     // 父节点编号（关联父节点的chapterNo）
}

// el-tree所需的前端渲染格式
interface TreeChapter extends BackendChapter {
	label: string; // el-tree显示字段（与name一致）
	children?: TreeChapter[]; // 子节点
}

const chapterNo = ref(0);
const currentNodeKey = ref(0);
const props = defineProps({
	data: {
		type: Array as () => BackendChapter[],
		default: () => []
	},
	maxLevel: {
		type: Number,
		default: 3
	},
	bookNo: {
		type: Number,
		required: true
	},
	courseNo: {
		type: Number,
		required: true
	},
	tab: {
		type: String
	},
	btn: {
		type: Boolean,
		default: true
	},
	expandAll: {
		type: Boolean,
		default: false
	}
})
const emit = defineEmits<{
	(e: 'update:data', value: BackendChapter[]): void;
	(e: 'node-added', node: BackendChapter): void;
	(e: 'node-updated', node: BackendChapter): void;
	(e: 'node-deleted', nodeId: number): void;
	(e: 'node-click', node: BackendChapter): void;
}>()

// 内部状态
const treeRef = ref()
const treeData = ref<TreeChapter[]>([])
const editDialogVisible = ref(false)  // 弹窗显示状态
const isAdd = ref(false)              // 是否为新增操作（区分编辑）

// 计算属性：根据tab类型获取当前关联的编号（bookNo或courseNo）
const currentNo = computed(() => {
	return props.tab === 'course' ? props.courseNo : props.bookNo;
});
// 编辑表单数据
const editFormData = reactive<Partial<BackendChapter>>({
	...(props.tab === 'course' ? { courseNo: currentNo.value } : { bookNo: currentNo.value }),
	chapterNo: 0,
	id: 0,
	name: '',
	orderNum: 1,
	parentNo: 0
})

// 表单验证规则
const formRules = {
	name: [{ required: true, message: '请输入章节名称', trigger: 'blur' }],
	orderNum: [{ required: true, message: '请输入序号', trigger: 'blur' }],
	chapterNo: [{ required: true, message: '请输入章节编号', trigger: 'blur' }]
}

// el-tree配置
const defaultProps = {
	children: 'children',
	label: 'label'
}

/**
 * 初始化树形结构（递归处理所有层级节点）
 */
const initTreeData = (backendData: BackendChapter[]): TreeChapter[] => {
	// 递归处理每个节点，添加label字段，保留原始children结构
	const convertNode = (node: BackendChapter): TreeChapter => {
		const treeNode: TreeChapter = {
			...node,
			label: node.name, // 补充label字段（与name一致）
			children: [] // 先初始化，后续递归填充
		};
		// 如果有子节点，递归处理子节点
		if (node.children && node.children.length > 0) {
			treeNode.children = node.children.map(child => convertNode(child));
		}else {
			// 没有子节点，说明是最子级，设置currentNodeKey
			currentNodeKey.value = node.chapterNo;
		}
		return treeNode;
	};

	// 对根节点数组进行转换
	return backendData.map(node => convertNode(node));
};

// 监听父组件数据变化
watch(() => props.data, (newVal) => {
	treeData.value = initTreeData(newVal);
}, { deep: true });
// 监听tab变化，同步更新表单中的关联编号
watch(() => props.tab, (newTab) => {
	if (newTab === 'course') {
		editFormData.courseNo = currentNo.value;
		delete editFormData.bookNo; // 移除不需要的字段
	} else {
		editFormData.bookNo = currentNo.value;
		delete editFormData.courseNo; // 移除不需要的字段
	}
});
// 获取节点层级
const getNodeLevel = (node: TreeChapter): number => {
	let level = 1;
	let parent = treeRef.value?.getNode(node)?.parent;
	while (parent && parent.level !== 0) {
		level++;
		parent = parent.parent;
	}
	return level;
};

// 新增根节点（章）
const appendRoot = () => {
	isAdd.value = true; // 标记为新增操作
	editDialogVisible.value = true; // 打开弹窗

	// 初始化根节点表单默认值
	const rootCount = treeData.value.length; // 当前根节点数量
	editFormData.id = '';
	editFormData.name = `第${rootCount + 1}章`; // 默认名称（如"第1章"）
	editFormData.orderNum = rootCount + 1; // 序号默认取当前根节点数量+1
	editFormData.parentNo = 0; // 根节点父编号固定为0
	editFormData.chapterNo = undefined

	// 根据tab类型设置关联编号（bookNo或courseNo）
	if (props.tab === 'course') {
		editFormData.courseNo = currentNo.value;
		delete editFormData.bookNo;
	} else {
		editFormData.bookNo = currentNo.value;
		delete editFormData.courseNo;
	}
	currentParent.value = null;
};
let currentParent = ref();
// 新增子节点（弹窗方式）
const append = (parentNode: TreeChapter) => {
	// 校验层级
	const level = getNodeLevel(parentNode);
	if (level >= props.maxLevel) {
		ElMessage.warning(`最多支持${props.maxLevel}级节点`);
		return;
	}

	// 初始化父节点children（避免undefined）
	if (!parentNode.children) parentNode.children = [];
	const childCount = parentNode.children.length;

	// 标记为新增状态，记录当前父节点
	isAdd.value = true;

	// 初始化表单默认值
	editFormData.id = '';
	editFormData.name = `${parentNode.name}第${childCount + 1}节`; // 默认名称
	editFormData.orderNum = childCount + 1; // 默认序号（后续节点自动+1）
	editFormData.parentNo = parentNode.chapterNo; // 关联父节点chapterNo
	// 章节编号默认规则：父编号*10 + 序号（如父1 -> 子11、12...）
	editFormData.chapterNo = undefined;
	if (props.tab === 'course') {
		editFormData.courseNo = currentNo.value;
		delete editFormData.bookNo;
	} else {
		editFormData.bookNo = currentNo.value;
		delete editFormData.courseNo;
	}

	// 打开弹窗
	editDialogVisible.value = true;
	currentParent.value = parentNode;
};
const originalNodeData = ref();
// 开始编辑节点
const startEdit = (node: TreeChapter) => {
	isAdd.value = false; // 标记为编辑状态

	originalNodeData.value = JSON.parse(JSON.stringify(node));
	// 回显节点数据
	editFormData.id = node.id;
	editFormData.name = node.name;
	editFormData.orderNum = node.orderNum;
	editFormData.chapterNo = node.chapterNo;
	editFormData.parentNo = node.parentNo;
	if (props.tab === 'course') {
		editFormData.courseNo = node.courseNo;
		delete editFormData.bookNo;
	} else {
		editFormData.bookNo = node.bookNo;
		delete editFormData.courseNo;
	}
	// 打开弹窗
	editDialogVisible.value = true;
};
const findParentNode = (nodes: TreeChapter[], parentNo: number): TreeChapter | null => {
	for (const node of nodes) {
		if (node.chapterNo === parentNo) {
			return node;
		}
		if (node.children && node.children.length > 0) {
			const found = findParentNode(node.children, parentNo);
			if (found) return found;
		}
	}
	return null;
};
// 确认编辑/新增
const confirmEdit = () => {
	if (isAdd.value) {
		// 校验表单必填项
		if (!editFormData.name || !editFormData.orderNum || !editFormData.chapterNo) {
			ElMessage.warning('请完善章节信息');
			return;
		}

		// 创建新节点
		const baseNode: TreeChapter = {
			chapterNo: editFormData.chapterNo as number,
			id: editFormData.id as number,
			name: editFormData.name as string,
			orderNum: editFormData.orderNum as number,
			parentNo: editFormData.parentNo as number,
			label: editFormData.name as string,
			children: []
		};
		const newNode: TreeChapter = props.tab === 'course'
			? { ...baseNode, courseNo: currentNo.value }
			: { ...baseNode, bookNo: currentNo.value };
		const parentNode = editFormData.parentNo === 0 ? null : findParentNode(treeData.value, editFormData.parentNo as number);

		// 关键：将新节点插入到树形结构中
		if (parentNode) {
			// 子节点：插入到父节点的children数组
			if (!parentNode.children) parentNode.children = [];
			parentNode.children.push(newNode);
		} else {
			// 根节点：直接插入到treeData
			treeData.value.push(newNode);
		}
		// 记录新增节点及父节点
		recordAddedNode(newNode, parentNode);
		// 触发新增事件
		emit('node-added', newNode);

	} else {
		// 编辑节点逻辑
		// 查找当前编辑的节点
		const findAndUpdateNode = (nodes: TreeChapter[]): boolean => {
			for (const node of nodes) {
				if (node.id === editFormData.id) {
					// 更新节点数据
					node.name = editFormData.name as string;
					node.orderNum = editFormData.orderNum as number;
					node.chapterNo = editFormData.chapterNo as number;
					node.label = editFormData.name as string;
					if (props.tab === 'course') {
						node.courseNo = currentNo.value;
					} else {
						node.bookNo = currentNo.value;
					}
					return true;
				}
				if (node.children && findAndUpdateNode(node.children)) {
					return true;
				}
			}
			return false;
		};

		// 执行更新
		const isUpdated = findAndUpdateNode(treeData.value);
		if (isUpdated) {
			const emitData: BackendChapter = props.tab === 'course'
				? {
					courseNo: currentNo.value,
					id: editFormData.id as number,
					name: editFormData.name as string,
					chapterNo: editFormData.chapterNo as number,
					orderNum: editFormData.orderNum as number,
					parentNo: editFormData.parentNo as number
				}
				: {
					bookNo: currentNo.value,
					id: editFormData.id as number,
					name: editFormData.name as string,
					chapterNo: editFormData.chapterNo as number,
					orderNum: editFormData.orderNum as number,
					parentNo: editFormData.parentNo as number
				};
			emit('node-updated', emitData);
		} else {
			ElMessage.error('未找到节点，编辑失败');
		}
	}

	// 关闭弹窗并同步数据
	editDialogVisible.value = false;
	syncToParent();
};

// 取消编辑/新增
const cancelEdit = () => {
	editDialogVisible.value = false;
	// 重置表单（避免下次打开时残留数据）
	Object.assign(editFormData, {
		name: '',
		orderNum: 1,
		chapterNo: 0,
		parentNo: 0,
		...(props.tab === 'course' ? { courseNo: currentNo.value } : { bookNo: currentNo.value })
	});
};

// 删除节点
const remove = (node: any, data: TreeChapter) => {
	ElMessageBox.confirm(`确定删除【${data.name}】吗？`, '提示', {
		type: 'warning'
	}).then(() => {
		const parent = node.parent;
		const children = parent.data.children || parent.data;
		const index = children.findIndex((item: TreeChapter) => item.id === data.id);
		if (index > -1) {
			children.splice(index, 1);
			// 重新计算子节点序号
			children.forEach((child: TreeChapter, i: number) => {
				child.orderNum = i + 1;
			});
			emit('node-deleted', data.id);
			syncToParent();
		}
	}).catch(() => {});
};

// 节点点击事件
const handleNodeClick = (data: TreeChapter) => {
	emit('node-click', { ...data });
	chapterNo.value = Number(data.chapterNo)
};

// 同步数据给父组件
const syncToParent = () => {
	const convertToBackend = (nodes: TreeChapter[]): BackendChapter[] => {
		return nodes.map(node => {
			const { label, ...backendNode } = node;
			return {
				...backendNode,
				children: node.children ? convertToBackend(node.children) : []
			};
		});
	};
	const backendData = convertToBackend(treeData.value);
	emit('update:data', backendData);
};
const lastAddedNode = ref<TreeChapter | null>(null);
const lastAddedParent = ref<TreeChapter | null>(null);

// 记录新增节点信息（在confirmEdit的新增逻辑中调用）
const recordAddedNode = (node: TreeChapter, parentNode: TreeChapter | null) => {
	lastAddedNode.value = node;
	lastAddedParent.value = parentNode;
};

// 回滚新增节点（暴露给父组件调用）
// 回滚新增节点（暴露给父组件调用）
const rollbackAddedNode = () => {
	if (!lastAddedNode.value) return;
	if (lastAddedParent.value) {
		// 1. 回滚子节点（有父节点的情况）
		const parentChildren = lastAddedParent.value.children || [];
		parentChildren.splice(-1, 1);
	} else {
		treeData.value.splice(-1, 1);
	}
	// 3. 同步数据并强制刷新树形结构
	syncToParent();

	// 4. 清空记录
	lastAddedNode.value = null;
	lastAddedParent.value = null;
};

const findNodeByChapterNo = (chapterNo: number | string, nodes: TreeChapter[]): TreeChapter | null => {
	for (const node of nodes) {
		if (node.chapterNo === chapterNo) {
			return node;
		}
		if (node.children && node.children.length > 0) {
			const found = findNodeByChapterNo(chapterNo, node.children);
			if (found) {
				return found;
			}
		}
	}
	return null;
};
watch(currentNodeKey, (newVal) => {
	if (newVal) {
		const targetNode = findNodeByChapterNo(newVal, treeData.value);
		if (targetNode) {
			handleNodeClick(targetNode);
		}
	}
});
onMounted(async ()=>{
	treeData.value = initTreeData(props.data);
})

// 暴露方法给父组件
defineExpose({
	appendRoot,
	getTreeData: (): BackendChapter[] => {
		return syncToParent() as unknown as BackendChapter[];
	},
	rollbackAddedNode,
	// 回滚节点数据（接口失败时调用）
	rollbackNode: () => {
		if (!originalNodeData.value) return;
		// 查找节点并覆盖为原数据
		const findAndRollback = (nodes: TreeChapter[]): boolean => {
			for (const node of nodes) {
				if (node.id === originalNodeData.value!.id) {
					// 用缓存的原数据覆盖当前节点
					Object.assign(node, originalNodeData.value);
					return true;
				}
				if (node.children && findAndRollback(node.children)) {
					return true;
				}
			}
			return false;
		};
		findAndRollback(treeData.value);
		// 同步回滚后的数据到父组件
		syncToParent();
	}
})
</script>

<style scoped lang="scss">
.tree-container {
	padding: 10px;

	:deep(.el-tree) {
		background: transparent;

		.el-tree-node__content {
			height: 40px;
			&:hover {
				background-color: #f5f7fa;
			}
		}
	}

	.empty-tree {
		padding: 20px;
		text-align: center;
		color: #999;
	}
}

.custom-tree-node {
	flex: 1;
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding-right: 10px;

	.node-label {
		flex: 1;
		white-space: break-spaces;

		.node-meta {
			margin-left: 10px;
			color: #666;
			font-size: 12px;
		}
	}

	.node-actions {
		opacity: 0;
		transition: opacity 0.3s;

		&:hover {
			opacity: 1;
		}

		.action-btn {
			margin-left: 5px;
		}
	}

	&:hover .node-actions {
		opacity: 1;
	}
}
</style>
